<?php

namespace App\utils;

use GuzzleHttp\Client;
use Illuminate\Support\Str;
use Overtrue\Pinyin\Pinyin;

class TopicTranslater
{
    protected $api_url = 'https://fanyi-api.baidu.com/api/trans/vip/translate?';
    protected $appid = null;
    protected $appkey = null;

    public function __construct(){
        $this->appid = config('services.baidu_translate.appid');
        $this->appkey = config('services.baidu_translate.key');
    }

    public function translate($text){

        if(empty($this->appid) || empty($this->appkey)){
            $result = $this->pinyin($text);
        }else{
            $result = $this->baidu($text);
        }

        //主要翻译出错
        if(false===$result){
            return $this->pinyin($text);
        }

        return $result;
    }

    /*
     * 百度api
     * */
    public function baidu($text){
        $http = new Client();
        $salt = time();

        $sign = md5($this->appid.$text.$salt.$this->appkey);

        $query = http_build_query([
            'q'=>$text,
            'from'=>'zh',
            'to'=>'en',
            'appid'=>$this->appid,
            'salt'=>$salt,
            'sign'=>$sign,
        ]);


        $response = $http->get($this->api_url.$query);
        $result = json_decode($response->getBody(),true);


        if(isset($result['trans_result'][0]['dst'])){
            return Str::slug($result['trans_result'][0]['dst']);
        }else{
            return false;
        }
    }

    /*
     * 备选方案：本地拼音
     * */
    public function pinyin($text){

        return Str::slug(app(Pinyin::class)->permalink($text));
    }

}
